package com.roadmap.common;

import java.lang.reflect.Method;
import java.util.Date;

public abstract class BaseEntity {
	private String id;
	private Date createdTime;
	private Date updatedTime;

	/** the entity can be called by this property, just like a person's name */
	private String whatItIs;
	/** the max length of the text which describes the entity */
	protected final static int DESP_MAX_LENGTH = 20;
	private int commentCount;

	public BaseEntity() {
		this.id = null;
		Date dt = new Date();
		this.createdTime = dt;
		this.updatedTime = dt;
	}

	public BaseEntity(String id) {
		this.id = id;
		Date dt = new Date();
		this.createdTime = dt;
		this.updatedTime = dt;
	}

	public BaseEntity(String id, Date createdTime, Date updatedTime) {
		this.id = id;
		this.createdTime = createdTime;
		this.updatedTime = updatedTime;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Date getCreatedTime() {
		return createdTime;
	}

	public void setCreatedTime(Date createdTime) {
		this.createdTime = createdTime;
	}

	public Date getUpdatedTime() {
		return updatedTime;
	}

	public void setUpdatedTime(Date updatedTime) {
		this.updatedTime = updatedTime;
	}

	/** the text which can explain what the entity is */
	public String getWhatItIs() {
		return whatItIs;
	}

	@Deprecated
	protected void setWhatItIs(String desp) {
		if (desp != null) {
			this.whatItIs = (desp.length() <= DESP_MAX_LENGTH) ? desp : (desp
					.substring(0, DESP_MAX_LENGTH) + "...");
		}
		else {
			this.whatItIs = "Entity";
		}
	}

	/** 将一个实体的属性值复制给当前对象的相应属性 */
	public void copyValues(BaseEntity entity) {
		if (entity == null) {
			return;
		}

		Method[] methods = entity.getClass().getMethods();
		for (Method m : methods) {
			// 找到getter
			if (m.getName().contains("get")) {
				try {
					// 找相应的setter
					String name = m.getName().replaceFirst("get", "set");
					Method ms = this.getClass().getMethod(name,
							m.getReturnType());
					Object val = m.invoke(entity);
					ms.invoke(this, val);
				}
				catch (Exception e) {
					// 不做任何事
				}
			}
		}
	}

	public int getCommentCount() {
		return commentCount;
	}

	public void setCommentCount(int commentCount) {
		this.commentCount = commentCount;
	}
}
